<?php

/**
 * 
 */
class Addthumb extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('thumbs_model');
        $this->load->model('reports_model');
    }

    public function insert() {
        $decision = $this->input->post('dec');
        $id = $this->input->post('id');
        $user_id = $this->session->userdata("sess_user_id");
        if ($user_id != null) {
            if (($this->thumbs_model->insertThumb($this->parseDecision($decision), $id, $user_id)) == 'ok') {
                $this->reports_model->plusOneThumb($id, $this->parseDecision($decision));
                echo "ok";
            } else {
                echo "voted";
            }
        }
    }

    public function parseDecision($dec) {
        switch ($dec) {
            case 'thumbDown':
                $dec_db = 'down';
                break;
            case 'thumbUp':
                $dec_db = 'up';
                break;
        }
        return $dec_db;
    }

    public function getThumbs($id) {
        if ($this->thumbs_model->fetchThumbById($id) != null) {
            $data['thumbs_arr'] = $this->thumbs_model->fetchThumbById($id);

            foreach ($data['thumbs_arr'] as $key) {
                $plus = $this->thu++;
                $data['t_decision'][$plus] = $key['decision']; // 
                $data['t_count'][$plus] = $key['count'];
            }

            if (count($data['thumbs_arr']) == 1) {

                if ($data['thumbs_arr'][0]['decision'] == 'up') {
                    $up_count = $data['thumbs_arr'][0]['count'];
                    $down_count = 0;
                } else {
                    $down_count = $data['thumbs_arr'][0]['count'];
                    $up_count = 0;
                }
            } else {
                $up_count = $data['thumbs_arr'][0]['count'];
                $down_count = $data['thumbs_arr'][1]['count'];
            }

            $num_of_thumbs = $up_count + $down_count;
            $data['tups'] = $up_count;
            $data['dups'] = $down_count;

            $data['percent_tup'] = floor(($up_count / $num_of_thumbs) * 100);
            $data['percent_dup'] = floor(($down_count / $num_of_thumbs) * 100);
            if ($data['percent_tup'] + $data['percent_dup'] != 100) {
                $data['percent_tup'] = $data['percent_tup'] + 1;
            }


            if ($this->session->userdata("sess_user_id")) {
                $user_id = $this->session->userdata("sess_user_id");
                if ($this->thumbs_model->hasVoted($user_id, $id)) {
                    $arr = $this->thumbs_model->hasVoted($user_id, $id);
                    $data['decision'] = $arr['decision'];
                }
            }
        }
        $this->load->view('templates/thumbs', $data);
    }

}
